﻿using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using SelfService.Helpers;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;

namespace SelfService.Controllers.Apis
{
    [ActionDescription("大屏队列")]
    [ApiController]
    [Route("api/queue")]
    [AuthorizeJwtWithCookie]
    public class ScreenQueueController : BaseApiController
    {
        private readonly IScreenQueueService _queueService;

        public ScreenQueueController(IScreenQueueService queueService)
        {
            _queueService = queueService;
        }

        /// <summary>
        /// 接收大屏队列信息的接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Public]
        public async Task<ActionResult> Post()
        {
            try
            {
                Request.EnableBuffering();
                Request.Body.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync();
                this.Logger($"预约系统大屏数据推送:{body}");
                var data = _queueService.Process(body);
                return this.Json(data);
            }
            catch (Exception e)
            {
                this.Logger($"接收大屏数据异常:{JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return BadRequest();
            }
        }

        /// <summary>
        /// 获取大屏队列信息
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost("GetQueueList")]
        [Public]
        public async Task<Result<object>> Get([FromBody]GetQueueListValidate post)
        {
            try
            {
                //查询客户端
                var client = await this.GetClientAsync();
                if (client == null)
                {
                    return new Result<object>()
                    {
                        Code = 1,
                        Message = "无效客户端"
                    };
                }
                this.Logger($"客户端:{client.Entity.Name}获取大屏队列信息");
                SysScreenQueue[] queue = default;
                if (post.QueueId != null && post.QueueId != Guid.Empty)
                {
                    var last = await DC.Set<SysScreenQueue>().FirstOrDefaultAsync(e => e.ID == post.QueueId);
                    queue = await DC.Set<SysScreenQueue>()
                        .CheckEqual(post.RoomId, e => e.RoomId)
                        .CheckEqual(post.DoctorId, e => e.DoctorId)
                        .Where(e => e.CreateTime > last.CreateTime)
                        .OrderBy(e => e.CreateTime)
                        .ToArrayAsync();
                }
                else
                {
                    queue = await DC.Set<SysScreenQueue>()
                        .CheckEqual(post.RoomId, e => e.RoomId)
                        .CheckEqual(post.DoctorId, e => e.DoctorId)
                        .OrderByDescending(e => e.CreateTime)
                        .Take(1)
                        .ToArrayAsync();
                }
                return new Result<object>
                {
                    Data = queue
                };
            }
            catch (Exception e)
            {
                this.Logger($"获取大屏队列异常: {JsonConvert.SerializeObject(e)}", ActionLogTypesEnum.Exception);
                return new Result<object>()
                {
                    Code = 1,
                    Message = "获取大屏队列异常"
                };
            }
        }
    }

    /// <summary>
    /// 获取队列信息校验类
    /// </summary>
    public class GetQueueListValidate
    {
        public Guid? QueueId { get; set; }

        [Required]
        public Guid RoomId { get; set; }

        public Guid? DoctorId { get; set; }
    }
}
